//
//  QGAdHocListController.m
//  RepairFactory
//
//  Created by heew on 15/12/5.
//  Copyright © 2015年 qeegoo. All rights reserved.
//

#import "QGAdHocListController.h"
#import "QGAdhocCell.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"
#import "RTSpinKitView.h"
#import "YYClassInfo.h"
#import "NSObject+YYModel.h"

#define SV_APP_EXTENSIONS
@interface QGAdHocListController () <UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *adhocList; /**测试版本列表 */
@property (strong, nonatomic) RTSpinKitView *spinkView; /**动画 */
@end

@implementation QGAdHocListController
+ (void)load {
    UINavigationBar *navBar = [UINavigationBar appearance];
    [navBar setBackgroundImage:[UIImage imageNamed:@"nav_bar_image.png"] forBarMetrics:UIBarMetricsDefault];
    [navBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    navBar.backItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    navBar.backItem.backBarButtonItem.tintColor = [UIColor redColor];
}
- (NSMutableArray *)adhocList {
    if (_adhocList == nil) {
        _adhocList = [NSMutableArray array];
    }
    return _adhocList;
}
- (RTSpinKitView *)spinkView {
    if (_spinkView == nil) {
        RTSpinKitView *spinkView = [[RTSpinKitView alloc] initWithStyle:RTSpinKitViewStyleCircleFlip color:[UIColor colorWithRed:0.91 green:0.3 blue:0.24 alpha:1.0]];
        [self.view addSubview:spinkView];
        CGRect screenBounds = [[UIScreen mainScreen] bounds];
        spinkView.center = CGPointMake(CGRectGetMidX(screenBounds), CGRectGetMidY(screenBounds));
        _spinkView = spinkView;
    }
    return _spinkView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"内测版本列表";
    self.tabBarItem.title = @"下载";
    self.tabBarItem.image = [UIImage imageNamed:@"download"];
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self.tableView.header beginRefreshing];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 100;
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"设置通知"
//                                                                             style:UIBarButtonItemStylePlain
//                                                                            target:self
//                                                                            action:@selector(setting:)];
    
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    NSDictionary *dict = @{@"uKey" : @"2168f4055437399fdfb0aeb0949cd96b",
                           @"_api_key" : @"2c103d0ef519c00e4a41dd9428e9d81b"};
    [mgr POST:@"http://www.pgyer.com/apiv1/user/listMyPublished" parameters:dict constructingBodyWithBlock:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)setting:(UIBarButtonItem *)sender {
    
    UIUserNotificationType type = [[UIApplication sharedApplication] currentUserNotificationSettings].types;
    NSLog(@"%lu",(unsigned long)type);
    NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
        
    }
}

- (void)loadNewData
{
    [self.spinkView startAnimating];
    [self.adhocList removeAllObjects];
    [self.tableView reloadData];
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    NSMutableURLRequest *request1 = nil;
    NSMutableURLRequest *request2 = nil;
    NSMutableURLRequest *request3 = nil;
    NSMutableURLRequest *request4 = nil;
    AFHTTPRequestOperation *op1 = nil;
    AFHTTPRequestOperation *op2 = nil;
    AFHTTPRequestOperation *op3 = nil;
    AFHTTPRequestOperation *op4 = nil;
    [op2 addDependency:op1];
    [op3 addDependency:op2];
    [op4 addDependency:op3];
    NSDictionary *param1 = @{@"aId" : @"763c02c118282e25e9d8293a1c9e0916",
                             @"_api_key" : @"0f100573a132929b1fc0abc9d3e72615"};
    NSDictionary *param2 = @{@"aId" : @"7e40b240a17f3a8fef2f7df285830826",
                             @"_api_key" : @"0f100573a132929b1fc0abc9d3e72615"};
    NSDictionary *param3 = @{@"aId" : @"29b19765f99b642b72c6683f679cf17a",
                             @"_api_key" : @"2c103d0ef519c00e4a41dd9428e9d81b"};
    NSDictionary *param4 = @{@"aId" : @"7372f066b047128f5860ef7c22470b4c",
                             @"_api_key" : @"2c103d0ef519c00e4a41dd9428e9d81b"};
    request1 = [serializer requestWithMethod:@"POST"
                                   URLString:@"http://www.pgyer.com/apiv1/app/viewGroup"
                                  parameters:param1
                                       error:nil];
    request2 = [serializer requestWithMethod:@"POST"
                                   URLString:@"http://www.pgyer.com/apiv1/app/viewGroup"
                                  parameters:param2
                                       error:nil];
    request3 = [serializer requestWithMethod:@"POST"
                                   URLString:@"http://www.pgyer.com/apiv1/app/viewGroup"
                                  parameters:param3
                                       error:nil];
    request4 = [serializer requestWithMethod:@"POST"
                                   URLString:@"http://www.pgyer.com/apiv1/app/viewGroup"
                                  parameters:param4
                                       error:nil];
    op1 = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
    op2 = [[AFHTTPRequestOperation alloc] initWithRequest:request2];
    op3 = [[AFHTTPRequestOperation alloc] initWithRequest:request3];
    op4 = [[AFHTTPRequestOperation alloc] initWithRequest:request4];
    NSMutableArray *mutableOperations = [NSMutableArray array];
//    [mutableOperations addObject:op1];
//    [mutableOperations addObject:op2];
    [mutableOperations addObject:op3];
    [mutableOperations addObject:op4];
    NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
    } completionBlock:^(NSArray *operations) {
        for (AFURLConnectionOperation *operation in operations) {
            NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                                           options:NSJSONReadingMutableLeaves
                                                                             error:nil];

               [self.adhocList addObjectsFromArray:[NSArray modelArrayWithClass:[QGAdHocApp class] json:responseObject[@"data"]]];
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
        [self.spinkView stopAnimating];
    }];
    [[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];}
#pragma mark - tableView datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.adhocList.count;
}

// 每一个行的细节
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    QGAdhocCell *cell = [QGAdhocCell cellWithTableView:tableView];
    QGAdHocApp *app = self.adhocList[indexPath.row];
    cell.app = app;
    return cell;
}
#pragma mark - tableView delegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    QGAdHocApp *app = self.adhocList[indexPath.row];
    NSString *appUrlString = [NSString stringWithFormat:@"itms-services://?action=download-manifest&url=https://www.pgyer.com/app/plist/%@",app.appKey];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appUrlString]];
//    [SVProgressHUD showSuccessWithStatus:@"已经开始安装,按home查看安装进度"];
}
@end

@implementation QGAdHocApp
@end
